package config

import (
	"context"
	"fmt"
	"log"
	"strconv"

	"github.com/go-redis/redis/v8"
)

type RedisClient struct {
	Client *redis.Client
}

var R *RedisClient

// redis 初始化
func InitRedis() {
	addr := ConfigInstance.Redis.Host + ":" + strconv.Itoa(ConfigInstance.Redis.Port)

	// 判断是否启用
	if ConfigInstance.Redis.Use {
		log.Println("Init Redis config ...")

		R = &RedisClient{
			Client: redis.NewClient(&redis.Options{
				Addr:     addr,
				Password: ConfigInstance.Redis.Password, // 无密码
				DB:       ConfigInstance.Redis.DB,       // 默认DB
			}),
		}

		// 创建一个默认的上下文
		ctx := context.Background()

		_, err := R.Client.Ping(ctx).Result()
		if err != nil {
			log.Fatalf("Could not connect to Redis: %v", err)
		}

		log.Println("Successfully connected to Redis")
	}
}

func (r *RedisClient) SetValue(key string, value string) error {
	if r.Client == nil {
		return fmt.Errorf("Redis client is not initialized")
	}
	ctx := context.Background()
	return r.Client.Set(ctx, key, value, 0).Err()
}

func (r *RedisClient) GetValue(key string) (string, error) {
	if r.Client == nil {
		return "", fmt.Errorf("Redis client is not initialized")
	}
	ctx := context.Background()
	return r.Client.Get(ctx, key).Result()
}
